import "dart:convert";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/bill/api.dart";
import "package:ct_pa_majordomo/pages/bill/bill_collecting/index.dart";
import "package:ct_pa_majordomo/pages/bill/widgets/show_multi_date_picker.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/utils/storage.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/divider/solid_divider.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/filter_dropdown.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/filter_header.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/index.dart";
import "package:ct_pa_majordomo/widgets/tai_dialog/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

class DueInDetail extends StatefulWidget {
  final Map? params;
  const DueInDetail({super.key, this.params});

  @override
  State<StatefulWidget> createState() => _DueInDetailState();

}

class _DueInDetailState extends State<DueInDetail> {
  final ScrollController _scrollController = ScrollController();
  final List<FilterHeaderItem> _headerItems = [
    FilterHeaderItem(title: "类型"),
    FilterHeaderItem(
      title: "数量：0",
      render: (title) {
        return Text(
          title,
          textAlign: TextAlign.center,
          style: const TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w500,
          ),
        );
      },
    ),
  ];
  final List _type = [{"name": "全部", "value": ""}, {"name": "即将到期", "value": "1"}, {"name": "逾期", "value": "2"}];
  final List _operation = [{
    "label": "公寓收款码",
    "value": 0,
  }, {
    "label": "完成收款",
    "value": 1,
  }, {
    "label": "催缴",
    "value": 2,
  }, {
    "label": "删除账单",
    "value": 3,
  }, {
    "label": "冻结钥匙",
    "value": 4,
  }];
  Map _filter = {
    "pageNum": 1,
    "pageSize": 10,
    "status": 1,
    "beginTime": null,
    "endTime": null,
  };
  Map<String, DateTime> _dateRange = {
    "startDate": DateTime.now(),
    "endDate": DateTime.now(),
  };
  List _list = [];
  double _dueInTotalMoney = 0;
  int _total = 0;
  late Map _user;


  Widget _littleRow({ required String label, required String value }) {
    return Row(
      children: [
        Text("$label："),
        Text(value),
      ],
    );
  }

  double _toDouble(dynamic data) {
    try {
      if (data is int || data is num) {
        return data.toDouble();
      } else if (data is String) {
        return double.parse(data);
      } else if (data is double) {
        return data;
      }
    } catch (error) {
      print("toDouble error:>>>>> $error");
    }

    return 0;
  }

  void _showQRCode(BuildContext context) {
    String qrUrl = "https://www.ctqct.net/weixin/index";
    Utils.showQRCode(context, url: qrUrl, title: "公寓收款码");
  }

  void _showBottomSheet(Map bill) async {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (BuildContext context) {
        return Container(
          width: double.infinity,
          padding: const EdgeInsets.all(ThemeVars.paddingPage),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Container(
                decoration: const BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(5)),
                    color: Colors.white
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: List.generate(_operation.length * 2 - 1, (index) {
                    if (index.isOdd) {
                      return const SolidDivider();
                    }
                    Map item = _operation[index ~/ 2];
                    return GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () {
                        Navigator.of(context).pop();
                        switch (item["value"]) {
                          case 0:
                            _showQRCode(context);
                            break;
                          case 1:
                            Stacker.pushNamed(Keys.BILL_COLLECTING, arguments: bill)
                              .then((value) {
                                if (value != null && value as bool) {
                                  _refresh();
                                }
                              });
                            break;
                          case 2:
                            break;
                          case 3: // 删除账单
                            taiDialog(
                              context: context,
                              child: const Text("确定删除账单？", textAlign: TextAlign.center,),
                              onConfirm: (taiContext) async {
                                await _removeBill(bill["billId"]);
                                _refresh();
                                if (taiContext.mounted) {
                                  Navigator.of(taiContext).pop();
                                }
                              }
                            );
                            break;
                          case 4:
                            break;
                        }
                      },
                      child: SizedBox(
                        height: 48,
                        child: Center(
                          child: Text(item["label"]),
                        ),
                      ),
                    );
                  }),
                ),
              ),
              const SizedBox(height: 12,),
              Button(
                  type: ButtonType.normal,
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: const Text("取消", style: TextStyle(color: ThemeVars.colorText),)
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _diffDaysText(String formattedString) {
    int diffDays = DateTime.parse(formattedString).difference(DateTime.now()).inDays;
    if (diffDays >= 0 && diffDays <= 3) {
      return Text("今天", style: TextStyle(color: ThemeVars.colorWarning),);
    } else if (diffDays > 3) {
      return Text("$diffDays天后", style: TextStyle(color: ThemeVars.colorTextTer),);
    } else {
      return Text("$diffDays天前", style: TextStyle(color: ThemeVars.colorError),);
    }
  }

  Widget _renderEmpty() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Icon(Icons.hourglass_empty_outlined, color: ThemeVars.colorPrimaryLight, size: 80,),
          SizedBox(height: 50,),
          Text("温馨提示：可以在【入住详情】中添加待收账单", style: TextStyle(fontSize: 12, color: ThemeVars.colorTextSec),),
        ],
      ),
    );
  }

  void _getBillList() async {
    try {
      EasyLoading.show();
      Map<String, dynamic> params = { ..._filter };
      Map resData = await billApi.getBillList(params);
      EasyLoading.dismiss();
      List data = resData["data"]["rows"] ?? [];
      setState(() {
        _headerItems.last.title = "数量：${resData["data"]["total"] ?? 0}";
        _list.addAll(data);
        _total = resData["data"]["total"] ?? 0;
        _dueInTotalMoney = _toDouble(resData["data"]["dueInTotalMoney"]);
        print("ssss:>>> $_total");
        print("ssss:>>> $data");
      });
    } catch(error) {
      EasyLoading.dismiss();
      print(error);
    }
  }

  Future<void> _removeBill(int billId) async{
    await billApi.removeBill(billId);
    EasyLoading.showToast("删除成功");
  }

  String _getFilterDateRange(dynamic startTime, dynamic endTime) {
    String tsStartTime = DateTools.formatYMD(startTime, format: "{y}.{m}.{d}");
    String tsEndTime = DateTools.formatYMD(endTime, format: "{y}.{m}.{d}");
    if (tsStartTime.isNotEmpty && tsEndTime.isNotEmpty) {
      return "$tsStartTime - $tsEndTime";
    }
    return "时间筛选";
  }

  Future<void> _refresh() async {
    setState(() {
      _list = [];
      _filter["pageNum"] = 1;
    });
    _getBillList();
  }

  void _onScroll() {
    if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
      print("判断前：》》》${_list.length} --- $_total");
      if (_list.length < _total) {
        setState(() {
          _filter["pageNum"] += 1;
        });
        _getBillList();
      }
    }
  }

  @override
  void initState() {
    super.initState();
    setState(() {
    if (widget.params != null) {
        _filter["billDate"] = widget.params?["status"];
        _headerItems[0].title = widget.params?["name"];
    }
    String info = storage.getString("info") ?? "";
    _user = jsonDecode(info);
    });
    _refresh();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return Container(
      child: FilterLayout(
          headerItems: _headerItems,
          dropdownItems: [
            FilterDropdownItem(
              items: _type,
              itemAsString: (item) => item["name"],
              onChanged: (item) =>
                setState(() {
                  _headerItems[0].title = item["name"];
                  _filter["billDate"] = item["value"];
                  _refresh();
                }),
            ),
          ],
          child: Stack(
            children: [
              RefreshIndicator(
                onRefresh: _refresh,
                child: _list.isNotEmpty ? ListView.separated(
                  controller: _scrollController,
                  padding: const EdgeInsets.fromLTRB(ThemeVars.paddingPage, 48, ThemeVars.paddingPage, ThemeVars.paddingPage),
                  itemCount: _list.length,
                  itemBuilder: (context, index) {

                    Map item = _list[index];
                    Map room = item["room"] ?? {};

                    return Container(
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(8)),
                      ),
                      child: GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {
                          _showBottomSheet(item);
                        },
                        child: Column(
                          children: [
                            Padding(
                              padding: EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 6),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Row(
                                    children: [
                                      Text(item["renterName"] ?? "--", style: TextStyle(fontWeight: FontWeight.w500, fontSize: 16),),
                                      SizedBox(width: 4,),
                                      Icon(Icons.phone_in_talk_rounded, color: ThemeVars.colorPrimary, size: 20,)
                                    ],
                                  ),
                                  Row(
                                    children: [
                                      Text("${item["name"]}：", style: TextStyle(fontWeight: FontWeight.w500),),
                                      Text("${item["money"].toStringAsFixed(2)}元", style: TextStyle(fontWeight: FontWeight.w500),)
                                    ],
                                  )
                                ],
                              ),
                            ),
                            SolidDivider(padding: EdgeInsets.only(left: ThemeVars.paddingPage),),
                            Padding(
                              padding: EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: ThemeVars.paddingPage),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.stretch,
                                children: [
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      _littleRow(label: "待收日期", value: DateTools.formatYMD(item["noticeDate"])),
                                      _diffDaysText(item["noticeDate"]),
                                    ],
                                  ),
                                  _littleRow(label: "账单周期", value: "${DateTools.formatYMD(item["billCycleBegin"])} - ${DateTools.formatYMD(item["billCycleEnd"])}"),
                                  Text("${room["buildingName"]}${room["name"]}")
                                ],
                              ),
                            )
                          ],
                        ),
                      ),
                    );
                  },
                  separatorBuilder: (context, index) => const SizedBox(height: 15),
                )
                : _renderEmpty(),
              ),
              Positioned(
                top: 0,
                left: 0,
                width: MediaQuery.of(context).size.width,
                child: Container(
                  height: 48,
                  padding: EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage),
                  decoration: BoxDecoration(
                    color: ThemeVars.colorBackground,
                    // color: Colors.white,
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      // Container(
                      //   padding: EdgeInsets.fromLTRB(12, 2, 6, 2),
                      //   decoration: BoxDecoration(
                      //       color: ThemeVars.colorDisabled,
                      //       borderRadius: BorderRadius.all(Radius.circular(20))
                      //   ),
                      //   child: Row(
                      //     children: [
                      //       GestureDetector(
                      //         behavior: HitTestBehavior.opaque,
                      //         onTap: () {
                      //           showMultiDatePicker(
                      //             context: context,
                      //             type: DateTimeType.range,
                      //             startDate: _dateRange["startDate"] ?? DateTime.now(),
                      //             endDate: _dateRange["endDate"] ?? DateTime.now(),
                      //             onchange: (dateRange) {
                      //               setState(() {
                      //                 _dateRange["startDate"] = DateTime.parse(dateRange[0]);
                      //                 _dateRange["endDate"] = DateTime.parse(dateRange[1]);
                      //                 _filter["beginTime"] = dateRange[0];
                      //                 _filter["endTime"] = dateRange[1];
                      //                 _getBillList();
                      //               });
                      //             },
                      //           );
                      //         },
                      //         child: Text(_getFilterDateRange(_filter["beginTime"], _filter["endTime"]), style: TextStyle(color: Colors.white,),),
                      //       ),
                      //       Icon(Icons.arrow_drop_down, color: Colors.white,)
                      //     ],
                      //   ),
                      // ),
                      Row(
                        children: [
                          Text("待收：", style: TextStyle(color: ThemeVars.colorTextSec, fontSize: 12,),),
                          Text(_dueInTotalMoney.toStringAsFixed(2), style: TextStyle(color: ThemeVars.colorSuccess, fontSize: 12,),)
                        ],
                      )
                    ],
                  ),
                ),
              )
            ],
          )
      ),
    );
  }

}